﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace VideoLib.Utils
{
    public class FFmpegHelper
    {
        public static string ffmpegPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ffmpeg\\ffmpeg.exe");

        public static async Task GenerateVideoPreview(string videoPath, string imagePath, string timeStamp)
        {

            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = ffmpegPath,
                Arguments = $"-hwaccel cuda -ss {timeStamp} -i \"{videoPath}\"  -frames:v 1 \"{imagePath}\"",
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };

            await Task.Run(() =>
            {
                using (Process ffmpegProcess = new Process { StartInfo = startInfo })
                {
                    ffmpegProcess.Start();
                    ffmpegProcess.BeginOutputReadLine();
                    ffmpegProcess.BeginErrorReadLine();
                    ffmpegProcess.WaitForExit();
                }
            });

        }

        public static async Task<TimeSpan> GetVideoDuration(string videoPath)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo(ffmpegPath, $"-i \"{videoPath}\"")
            {
                UseShellExecute = false,
                RedirectStandardError = true,
                CreateNoWindow = true
            };

            string durationString = string.Empty;
            await Task<TimeSpan>.Run(() =>
            {
                using (Process ffmpegProcess = Process.Start(startInfo))
                {
                    string output = ffmpegProcess.StandardError.ReadToEnd();
                    ffmpegProcess.WaitForExit();

                    durationString = Regex.Match(output, @"Duration: (\d{2}:\d{2}:\d{2}\.\d{2})").Groups[1].Value;
                }
            });

            return TimeSpan.Parse(durationString);
        }

        public static void GenerateVideoPreviews(string videoPath, string fileName, string outputFolder, double startSeconds, double intervalSeconds, int count)
        {
            string startTimestamp = TimeSpan.FromSeconds(startSeconds).ToString(@"hh\:mm\:ss");
            string fps = (1 / intervalSeconds).ToString("f2");

            string arguments = $"-hwaccel cuda -ss {startTimestamp} -i \"{videoPath}\" -vf \"fps={fps},scale=320:-1\" -frames:v {count} \"{outputFolder}\\{fileName}_%d.png\"";
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = ffmpegPath,
                Arguments = arguments,
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };

            using (Process ffmpegProcess = new Process { StartInfo = startInfo })
            {
                ffmpegProcess.Start();
                ffmpegProcess.BeginOutputReadLine();
                ffmpegProcess.BeginErrorReadLine();
                ffmpegProcess.WaitForExit();
            }
        }
    }
}
